// index.js
import {
  Post,
  Get
} from "../../utils/request.js"
let cur_id, cur_serid
Page({
  /**
   * 页面的初始数据
   */
  data: {
    bluetooths: [],
    Devices: [],
    loading: false,
    imgUrls: [{
      link: '/pages/index/index',
      url: '../../img/111.png'
    }, {
      link: '/pages/list/list',
      url: '../../img/111.png'
    }],
    shangdata: [{
        picture: '../../img/111.png',
        title: '这是标题这是标题这是标题这是标题这是标题这是标题',
        price: '1111',
        piece: '15',
      },
      {
        picture: '../../img/111.png',
        title: '这是标题这是标题这是标题这是标题这是标题这是标题',
        price: '1111',
        piece: '15',
      },
      {
        picture: '../../img/111.png',
        title: '这是标题这是标题这是标题这是标题这是标题这是标题',
        price: '1111',
        piece: '15',
      },
    ],
    indicatorDots: true, //小点
    indicatorColor: "white", //指示点颜色
    activeColor: "coral", //当前选中的指示点颜色
    autoplay: true, //是否自动轮播
    interval: 3000, //间隔时间
    duration: 300, //滑动时间
    circular: true, //是否衔接

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res, '发送 res.code 到后台换取')
        Get("/wx/user/wx38e17bf12e912a3b/login", {
            appid: 'wx38e17bf12e912a3b',
            code: res.code,
          })
          .then(res => {
            if (res.data!=="") {
              wx.setStorageSync('token', res.data)
              this.hehehheh()
            }
            
            console.log(res, "shuju")
          })
      }
    })
  


  },
  hehehheh:function(){
    // if(wx.getStorageSync('token')){
      // Get("/cabinet/code/{code}", {
      // })
      // .then(res => {
      //   console.log(res, "轮播图s")
      //   if(res.success){
      //     this.setData({
      //       imgUrls:res.data
      //     })
      //   }
  
      // })
  
    // }

  },
  getBluetoothDevices() {
    wx.getBluetoothDevices({
      success: ({
        devices
      }) => {
        this.setData({
          Devices: devices
        })
      
      }
    })

  },
  onDiscovery() {
    let loading = this.data.loading
    this.setData({
      loading: !loading
    })
    if (!loading) {
      let that = this;
      // wx.startBluetoothDevicesDiscovery   
      // 调用开启蓝牙
      return wx.startBluetoothDevicesDiscovery({
        success: function (res) {
          console.log(res, "调用开启蓝牙的接口")
          that.discoveryEvent()
        }
      })
    }
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res)
      }
    })
  },
  discoveryEvent() {
    wx.onBluetoothDeviceFound(({
      devices
    }) => {
      let bluetooths = devices;
      bluetooths.unshift(...this.data.bluetooths)
      this.setData({
        bluetooths
      })
    })
  },

  getBluetoothService() {},
  connection(event) {
    let bluetooth = event.currentTarget.dataset.d;
    if (!bluetooth) return
    let that = this;
    cur_id = bluetooth.deviceId
    this.setData({
      characteristics: []
    })
    wx.createBLEConnection({
      deviceId: bluetooth.deviceId,
      success: function (res) {
        wx.showToast({
          title: '蓝牙链接成功',
          icon: 'success',
          duration: 2000
        })
        //获取服务
        wx.getBLEDeviceServices({
          deviceId: bluetooth.deviceId,
          success: function ({
            services
          }) {
            console.log(services, "获取当前的id")
            that.setData({
              services: services
            })
          }
        })
      },
      fail: function (...args) {
        console.log(args)
        wx.showToast({
          title: '蓝牙连接失败',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  getBLEDeviceCharacteristics(event) {
    let id = event.currentTarget.dataset.d;
    cur_serid = id
    wx.getBLEDeviceCharacteristics({
      deviceId: cur_id,
      serviceId: id,
      success: ({
        characteristics
      }) => {
        this.setData({
          characteristics
        })

      }
    })
  },
  buf2hex: function (buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  },
  read(event) {
    let id = event.currentTarget.dataset.d;

    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log('characteristic value comed:', parseInt('0x' + this.buf2hex(characteristic.value)))
    })

    console.log(`${cur_id}======${cur_serid}======${id}`);

    this.setData({
      p: `${cur_id}======${cur_serid}======${id}`
    })

    setInterval(() => {
      wx.readBLECharacteristicValue({
        deviceId: cur_id,
        serviceId: cur_serid,
        characteristicId: id,
        success: (errMsg, characteristic) => {
          //  console.log(errMsg, characteristic)
        }
      })
    }, 1000)


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.showToast({
          title: '蓝牙已启动',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        wx.showToast({
          title: '请开启蓝牙',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.closeBluetoothAdapter({})
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})